//
//  ExportRecordView.swift
//  ptbuy
//。查看导出记录页面
//  Created by MyMac on 2024/12/5.
//

import SwiftUI
import CoreData

struct ExportRecordView: View {
    
    @Binding var exportRecord:Bool
    
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest(
        entity: Export.entity(),
        sortDescriptors: [NSSortDescriptor(
            keyPath: \Export.exportDate,
            ascending: false
        )],
        animation: .default
    ) private var export: FetchedResults<Export>
    
    
    @State private var fileName:String = ""
    
    @State private var navigateToDetailFail:Bool = false
    
    
    var body: some View {
        NavigationView {
            VStack{
                Divider()
                ScrollView {
                    VStack(spacing: 20) {
                        // 使用 ForEach 遍历数组
                        ForEach(export, id: \.self) { item in
                            VStack{
                                if item.clientid == "dengpp"{
                                    HStack{
                                        Spacer()
                                        Text("导出所有") .font(.system(size: 15))
                                        Spacer()
                                    }.padding()
                                }else{
                                    HStack{
                                        Text("客户名称:") .font(.system(size: 15))
                                        Spacer()
                                        Text(item.clientName ?? "").font(.system(size: 15))
                                    }.padding()
                                }
                                Divider()
                                HStack{
                                    Text("文件名称:") .font(.system(size: 15))
                                    Spacer()
                                    Text(item.exportFilePath ?? "").minimumScaleFactor(0.3).font(.system(size: 15))
                                }.padding()
                                Divider()
                                HStack{
                                    Text("导出日期:") .font(.system(size: 15))
                                    Spacer()
                                    Text(item.exportDate ?? "").minimumScaleFactor(0.3).font(.system(size: 15))
                                }.padding()
                                Divider() 
                                HStack{
                                    Spacer()
                                    Button(
                                        action: {
                                            if let name = item.exportFilePath{
                                                fileName = name
                                            }
                                            navigateToDetailFail = true
                                        }) {
                                            Text("查看文件") .font(.system(size: 15))
                                            
                                        }
                                        .buttonStyle(
                                            MyButtonStyle(width:100,size:15,height: 30)
                                        )
                                    Spacer()
                                }.padding()
                                
                            }.onAppear(){
                                if let clientId = item.clientid{
                                    searchClient(clientId:clientId,export:item)
                                }
                            }
                            .background(Color("endColor"))
                            .frame(maxWidth:.infinity)
                                .background(Color("endColor"))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(
                                            Color.black,
                                            lineWidth: 0.5
                                        ) // 设置边框
                                ).edgesIgnoringSafeArea(
                                    .all
                                ) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(10) // 设置最大宽高为无穷，确保视图覆盖全屏
                                .padding([.leading,.trailing])
                            
                        }
                    }
                }
            }.fullScreenCover(isPresented: $navigateToDetailFail){
                PdfViewer(fileName: $fileName,isPresented: $navigateToDetailFail)
            }.frame(maxWidth:.infinity,maxHeight: .infinity).background(
                // 创建渐变背景
                LinearGradient(
                    gradient: Gradient(
                        colors: [
                            Color("startColor").opacity(
                                10
                            ),
                            // 上半部分颜色，增加不透明度
                            Color("endColor").opacity(0.1)
                        ]// 上半部分颜色，增加不透明度
                    ),
                    startPoint: .top,
                    endPoint: .bottom
                )
                .edgesIgnoringSafeArea(.all)  // 确保背景覆盖整个屏幕
            ).navigationBarTitle("导出记录", displayMode: .inline).navigationViewStyle(
                StackNavigationViewStyle()
            ) // 推荐在全屏时使用此样式
            .background()
            .toolbar {
                // 修改标题字体大小
                ToolbarItem(placement: .topBarLeading) {
//                    Text("返回")
//                        .clipShape(
//                            Capsule()
//                        ) // 使用 Capsule 形状来实现圆角效果
//                        .onTapGesture {
//                            exportRecord = false
//                        }
                    Button(action: {       // 自定义返回动作
                        exportRecord = false
                        }) {
                            Image(systemName: "arrow.left.circle.fill") // 返回图标
                        }
                }
            }
        }
    }
    
    func searchClient(clientId:String,export:Export){
        let request: NSFetchRequest<Client> = Client.fetchRequest()
               // 设置查询条件，例如查询 amount > 10
        request.predicate = NSPredicate(format: "id = %@",clientId)
        do{
            let clients = try viewContext.fetch(request)
           
            for object in clients {
                
                export.clientName = object.name ?? ""
                
            }
       
        }catch{
            export.clientName =  ""
        }
    }
}
